package cn.icyzx.controller;

import cn.icyzx.models.Tag;
import cn.icyzx.models.Work;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import cn.icyzx.service.TagService;
import cn.icyzx.service.WorkService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.icyzx.util.WorksSelectCondition.TAG;
import static cn.icyzx.util.StaticConstUtil.*;

/**
 * @Author zk
 * @Date 2017/3/20.
 * @Email 2117251154@qq.com
 */
@Controller
@RequestMapping("/tag")
public class TagProcess {

    private static Logger logger = Logger.getLogger(TagProcess.class);

    @Autowired
    TagService tagService;

    @Autowired
    WorkService workService;

    /*** 根据标签查询
     *
     * @param modelAndView tag-page
     * @param tagName 查询的标签
     * @param curPage 当前页
     * @return
     */
    @RequestMapping(value = "/{tagName}/{curPage}", method = RequestMethod.GET)
    public ModelAndView tagPage(ModelAndView modelAndView, @PathVariable("tagName") String tagName,
                                @PathVariable("curPage") String curPage) {
        Map<String, String> condition = new HashMap<String, String>();
        condition.put(TAG, tagName);
        condition.put("curPage", curPage);
        List<Work> listWorks = workService.getlistWorks(condition);

        JSONObject page = new JSONObject();
        int sumPage = workService.getWorksPageSum(condition);
        page.put("sumPage", Integer.valueOf(sumPage));
        page.put("curPage", Integer.valueOf(curPage));
        page.put("condition", condition);

        Tag tag = tagService.getTagByTagName(tagName);
        List<Tag> hotTagList = tagService.getHotTagList();
        List<Work> hotWorkList = workService.getHotWork();

        modelAndView = new ModelAndView("tag-page");
        modelAndView.addObject("hotWorkList", hotWorkList);//热议作品
        modelAndView.addObject("hotTagList", hotTagList);//热门标签
        modelAndView.addObject("page", page);
        modelAndView.addObject("tag", tag);
        modelAndView.addObject("listWorks", listWorks);

        return modelAndView;
    }

    /**
     * 不带页码的请求，转发到一般的请求
     *
     * @param tag
     * @return
     */
    @RequestMapping(value = "/{tag}", method = RequestMethod.GET)
    public String tagPageNoPage(@PathVariable("tag") String tag) {
        return "forward:/tag/" + tag + "/1";
    }

    @RequestMapping(value = "/check", method = RequestMethod.POST)
    @ResponseBody
    String tagCheck(@RequestParam("tag") String tagName) {
        Tag tag = tagService.getTagByTagName(tagName);
        if (tag != null)
            return tag.getTagName();
        else return STATUS_FAIL;
    }
}
